//
//  KIDBAWAdvertisementManager.m
//  VISIKARD
//
//  Created by Phan Ba Minh on 9/5/12.
//  Copyright (c) 2012 kidbaw. All rights reserved.
//

#import "KIDBAWAdvertisementManager.h"
#import "AppViewController.h"

@implementation KIDBAWAdvertisementManager

- (id)init
{
    self = [super init];
    if (self) {
        // init list Banner Views
        _viewAdsList = [[NSMutableArray alloc] initWithCapacity:enumKIDBAWAdvertisementType_Sum];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    }
    return self;
}

- (void)dealloc
{
    _delegate = nil;
    [_viewAdsList removeAllObjects];
}

static KIDBAWAdvertisementManager *m_Instance;
+ (KIDBAWAdvertisementManager *)Shared {
    if ( !m_Instance ) {
        m_Instance = [KIDBAWAdvertisementManager new];
		
		NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:STRING_USER_DEFAULT_KIDBAW_ADVERTISEMENT_MANAGER];
        if ([NSKeyedUnarchiver unarchiveObjectWithData:data]) {
            //KIDBAWAdvertisementManager *_data = [[NSKeyedUnarchiver unarchiveObjectWithData:data] retain];
        }
    }
    return m_Instance;
}

#pragma mark - Actions

- (void)update {
    if (CFAbsoluteTimeGetCurrent() - _timeShowedAds > TIMER_SHOWING_BANNER && _isAllowed == enumKIDBAWAdvertisementIsAllowed_Showed) {
        [self hideAdsWithAnimation:_animationAds];
    }
    else if (CFAbsoluteTimeGetCurrent() - _timeShowedAds > TIMER_HIDING_BANNER && (_isAllowed == enumKIDBAWAdvertisementIsAllowed_Invalid || _isAllowed == enumKIDBAWAdvertisementIsAllowed_Hidden)) {
        [self showAdsWithAnimation:_animationAds];
    }
    
    if (CFAbsoluteTimeGetCurrent() - _timeReloadedAds > TIMER_RELOADING_BANNER && ![self checkFinishedStatus]) {
        _timeReloadedAds = CFAbsoluteTimeGetCurrent();
        [self loadInterface];
    }
    
//    UIViewController *tempVC = [[AppViewController Shared].listOfViewController lastObject];
//    _frameShowedAds = CGRectMake(_frameShowedAds.origin.x, _frameShowedAds.origin.y, tempVC.view.frame.size.width, _frameShowedAds.size.height);
//    _mainView.frame = _frameShowedAds;
//    if (_viewInstanceOld) _viewInstanceOld.frame = CGRectMake(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//    if (_viewInstanceNew) _viewInstanceNew.frame = CGRectMake(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
}

- (void)startAdsInView:(UIViewController *)viewcontroller andBannerFrame:(CGRect)frame andDelegate:(id<KIDBAWAdvertisementProtocol>)del {
    // Param
    _viewControllerAds = viewcontroller;
    _delegate = del;
    _frameShowedAds = frame;
    
    // Default
    _timeShowedAds = CFAbsoluteTimeGetCurrent();
    _priorityAds = enumKIDBAWAdvertisementPriority_iAd;
    _animationAds = enumKIDBAWAdvertisementAnimation_FromRightToLeft;
    
    // Interface
    [self loadInterface];
}

- (void)loadInterface {
    // Init
    [self initAds];
    [self loadNextAdsType];
    
    if ([_delegate respondsToSelector:@selector(loadInterfaceKIDBAWAdvertisementCallBack)]) {
        [_delegate loadInterfaceKIDBAWAdvertisementCallBack];
    }
}

- (void)initAds {
    if (_isAllowed == enumKIDBAWAdvertisementIsAllowed_Prevented) {
        return;
    }
    
    // Remove
    [_viewAdsList removeAllObjects];
    _viewInstanceOld = _viewInstanceNew = nil;
    
    // MAIN VIEW
    if (_mainView) {
        [[_mainView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_mainView removeFromSuperview];
        _mainView = nil;
    }
    _mainView = [[UIView alloc] initWithFrame:_frameShowedAds];
    [_viewControllerAds.view addSubview:_mainView];
    _mainView.hidden = YES;
    
    // BackGround
    if (_imgViewPlaceHolder) {
        [_imgViewPlaceHolder removeFromSuperview];
        _imgViewPlaceHolder = nil;
    }
    _imgViewPlaceHolder = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ads_placeholder.png"]];
    _imgViewPlaceHolder.frame = CGRectMake(0, - 4, _frameShowedAds.size.width, _frameShowedAds.size.height + 4);
    [_mainView addSubview:_imgViewPlaceHolder];
    
    for (int i = 0; i < enumKIDBAWAdvertisementType_Sum; i++) {
        UIView *adsView;
        
        switch (i) {
                // DON'T USE ADMOD, MOPUB
                
//            case enumKIDBAWAdvertisementType_MoPub: {
//                adsView = [[MPAdView alloc] initWithAdUnitId:MOPUB_BANNER_UNIT_ID size:MOPUB_BANNER_SIZE];
//                adsView.frame = CGRectMake(0, [SupportFunction getDeviceHeight], [SupportFunction getDeviceWidth], HEIGHT_KIDBAW_ADVERTISEMENT_BANNER);
//                ((MPAdView *)adsView).delegate = self;
//                [_viewAdsList addObject:adsView];
//                [_viewControllerAds.view addSubview:adsView];
//                adsView.hidden = YES;
//                break;
//            }
//            case enumKIDBAWAdvertisementType_AdMod:
//            {
//                adsView = [[GADBannerView alloc] initWithFrame:CGRectMake(0, [SupportFunction getDeviceHeight], WIDTH_KIDBAW_ADVERTISEMENT_BANNER, HEIGHT_KIDBAW_ADVERTISEMENT_BANNER)];
//                ((GADBannerView *)adsView).adUnitID = ADMOD_BANNER_UNIT_ID;
//                ((GADBannerView *)adsView).delegate = self;
//                ((GADBannerView *)adsView).rootViewController = _viewControllerAds;
//                [_viewAdsList addObject:adsView];
//                [_viewControllerAds.view addSubview:adsView];
//                adsView.hidden = YES;
//                break;
//            }
            case enumKIDBAWAdvertisementType_iAd:
            {
                adsView = [[ADBannerView alloc] initWithFrame:FRAME(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height)];
                ((ADBannerView *)adsView).delegate = self;
                ((ADBannerView *)adsView).currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
                [_viewAdsList addObject:adsView];
                [_mainView addSubview:adsView];
                break;
            }
            default:
                break;
        }
    }
    
    _indexAds = enumKIDBAWAdvertisementType_Invalid;
}

- (void)loadNextAdsType {
    // iAd
    int indexNew = (_indexAds + 1) % enumKIDBAWAdvertisementType_Sum;
//    NSLog(@"loadNextAdsType: %i, _priorityAds: %i", indexNew, _priorityAds);
    if (indexNew >= _viewAdsList.count) {
        return;
    }
    if ((_priorityAds & enumKIDBAWAdvertisementPriority_iAd) == enumKIDBAWAdvertisementPriority_iAd && indexNew == enumKIDBAWAdvertisementType_iAd) {
        _indexAds = indexNew;
        _viewInstanceNew = [_viewAdsList objectAtIndex:_indexAds];
        if (!_viewInstanceOld) {
            _viewInstanceOld = _viewInstanceNew;
        }
        [self refreshAds];
        return;
    }
    
    // AdMod
    indexNew = (indexNew + 1) % enumKIDBAWAdvertisementType_Sum;
    if (indexNew >= _viewAdsList.count) {
        return;
    }
    if ((_priorityAds & enumKIDBAWAdvertisementPriority_AdMod) == enumKIDBAWAdvertisementPriority_AdMod && indexNew == enumKIDBAWAdvertisementType_AdMod) {
        _indexAds = indexNew;
        _viewInstanceNew = [_viewAdsList objectAtIndex:_indexAds];
        if (!_viewInstanceOld) {
            _viewInstanceOld = _viewInstanceNew;
        }
        [self refreshAds];
        return;
    }
   
    // MobPub
    indexNew = (indexNew + 1) % enumKIDBAWAdvertisementType_Sum;
    if (indexNew >= _viewAdsList.count) {
        return;
    }
    if ((_priorityAds & enumKIDBAWAdvertisementPriority_MoPub) == enumKIDBAWAdvertisementPriority_MoPub && indexNew == enumKIDBAWAdvertisementType_MoPub) {
        _indexAds = indexNew;
        _viewInstanceNew = [_viewAdsList objectAtIndex:_indexAds];
        if (!_viewInstanceOld) {
            _viewInstanceOld = _viewInstanceNew;
        }
        [self refreshAds];
        return;
    }
    
    // can not load new ads type
    [self refreshAds];
}

- (BOOL)checkFinishedStatus {
    if (_statusAds == enumKIDBAWAdvertisementStatus_iAd_Finished || _statusAds == enumKIDBAWAdvertisementStatus_AdMod_Finished || _statusAds == enumKIDBAWAdvertisementStatus_MoPub_Finished || _statusAds == enumKIDBAWAdvertisementStatus_KIDBAW_Finished) {
        return YES;
    }
    return NO;
}

- (void)showAdsWithAnimation:(enumKIDBAWAdvertisementAnimation)animation {
    if ([self checkFinishedStatus]) {
//        NSLog(@"showAdsWithAnimation");
        if (_animationAds == enumKIDBAWAdvertisementAnimation_FromRightToLeft) {
            [self showAds];
            
            _isAllowed = enumKIDBAWAdvertisementIsAllowed_Showed;
            _timeShowedAds = CFAbsoluteTimeGetCurrent();
            
            // CASE 1:
            if (_viewInstanceNew && _viewInstanceOld) {
                _mainView.frame = CGRectMake(_frameShowedAds.size.width, _frameShowedAds.origin.y, _frameShowedAds.size.width, _frameShowedAds.size.height);
                [UIView transitionWithView:_viewInstanceOld
                                  duration:TIMER_CHANGING_VIEW
                                   options:UIViewAnimationOptionTransitionNone
                                animations:^{
                                    _mainView.frame = CGRectMake(0, _frameShowedAds.origin.y, _frameShowedAds.size.width, _frameShowedAds.size.height);
                                } completion:^(BOOL finished) {
                                    
                                }];
            }
            else {
                [self hideAds];
            }
            
//            // CASE 2:
//            if (_viewInstanceNew != _viewInstanceOld && _viewInstanceNew && _viewInstanceOld) {
//                _viewInstanceOld.frame = CGRectMake(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                _viewInstanceNew.frame = CGRectMake(_frameShowedAds.size.width, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                [UIView transitionWithView:_viewInstanceOld
//                                  duration:TIMER_CHANGING_VIEW
//                                   options:UIViewAnimationOptionTransitionNone
//                                animations:^{
//                                    _viewInstanceOld.frame = CGRectMake(-_frameShowedAds.size.width, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                                    _viewInstanceNew.frame = CGRectMake(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                                } completion:^(BOOL finished) {
//                                }];
//            }
//            else if (_viewInstanceNew == _viewInstanceOld && _viewInstanceNew && _viewInstanceOld) {
//                _viewInstanceOld.frame = CGRectMake(_frameShowedAds.size.width, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                _viewInstanceNew.frame = CGRectMake(_frameShowedAds.size.width, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                [UIView transitionWithView:_viewInstanceOld
//                                  duration:TIMER_CHANGING_VIEW
//                                   options:UIViewAnimationOptionTransitionNone
//                                animations:^{
//                                    _viewInstanceOld.frame = CGRectMake(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                                    _viewInstanceNew.frame = CGRectMake(0, 0, _frameShowedAds.size.width, _frameShowedAds.size.height);
//                                } completion:^(BOOL finished) {
//                                }];
//            }
//            else {
//                [self hideAds];
//            }
        }
        else {
            [self hideAds];
        }
    }
    else {
        [self hideAds];
    }
}

- (void)hideAdsWithAnimation:(enumKIDBAWAdvertisementAnimation)animation {
    if ([self checkFinishedStatus]) {
//        NSLog(@"hideAdsWithAnimation");
        if (_animationAds == enumKIDBAWAdvertisementAnimation_FromRightToLeft) {
            _isAllowed = enumKIDBAWAdvertisementIsAllowed_Hidden;
            _timeShowedAds = CFAbsoluteTimeGetCurrent();
            
            // MAIN VIEW
            [UIView transitionWithView:_viewInstanceOld
                              duration:TIMER_CHANGING_VIEW
                               options:UIViewAnimationOptionTransitionNone
                            animations:^{
                                _mainView.frame = CGRectMake(-_frameShowedAds.size.width, _frameShowedAds.origin.y, _frameShowedAds.size.width, _frameShowedAds.size.height);
                            } completion:^(BOOL finished) {
                                [self hideAds];
                            }];
        }
        else {
            [self hideAds];
        }
    }
    else {
        [self hideAds];
    }
}

- (void)showAds {
    if (_isAllowed != enumKIDBAWAdvertisementIsAllowed_Prevented) {
        _mainView.hidden = NO;
        _isAllowed = enumKIDBAWAdvertisementIsAllowed_Showed;
    }
}

- (void)hideAds {
    if (_isAllowed != enumKIDBAWAdvertisementIsAllowed_Prevented) {
        _mainView.hidden = YES;
        _isAllowed = enumKIDBAWAdvertisementIsAllowed_Hidden;
    }
}

- (void)preventAds {
    _mainView.hidden = YES;
    _isAllowed = enumKIDBAWAdvertisementIsAllowed_Prevented;
}

- (void)allowAds {
    _mainView.hidden = NO;
    if (_isAllowed == enumKIDBAWAdvertisementIsAllowed_Prevented) {
        _isAllowed = enumKIDBAWAdvertisementIsAllowed_Invalid;
    }
}

- (void)refreshAds
{
    if ((_priorityAds & enumKIDBAWAdvertisementPriority_iAd) == enumKIDBAWAdvertisementPriority_iAd && _indexAds == enumKIDBAWAdvertisementType_iAd) {
        
    }
    // DON'T USE ADMOD, MOPUB
    
//    else if ((_priorityAds & enumKIDBAWAdvertisementPriority_AdMod) == enumKIDBAWAdvertisementPriority_AdMod && _indexAds == enumKIDBAWAdvertisementType_AdMod) {
//        [((GADBannerView *)[_viewAdsList objectAtIndex:enumKIDBAWAdvertisementType_AdMod]) loadRequest:[GADRequest request]];
//    }
//    else if ((_priorityAds & enumKIDBAWAdvertisementPriority_MoPub) == enumKIDBAWAdvertisementPriority_MoPub && _indexAds == enumKIDBAWAdvertisementType_MoPub) {
//        [((MPAdView *)[_viewAdsList objectAtIndex:enumKIDBAWAdvertisementType_MoPub]) refreshAd];
//    }
}

#pragma mark - ADBannerViewDelegate
// Sent when an ad request failed.
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    if ((_priorityAds & enumKIDBAWAdvertisementPriority_iAd) == enumKIDBAWAdvertisementPriority_iAd && _indexAds == enumKIDBAWAdvertisementType_iAd) {
        NSLog(@"iAd didFailToReceiveAdWithError %@", error.description);
        [self loadNextAdsType];
        
        if (_isAllowed != enumKIDBAWAdvertisementIsAllowed_Prevented) {
            _statusAds = enumKIDBAWAdvertisementStatus_iAd_Failed;
            [self hideAdsWithAnimation:_animationAds];
        }
    }
}

// Sent when an ad request loaded an ad.
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    if ((_priorityAds & enumKIDBAWAdvertisementPriority_iAd) == enumKIDBAWAdvertisementPriority_iAd && _indexAds == enumKIDBAWAdvertisementType_iAd) {
        NSLog(@"iAd bannerViewDidLoadAd");
        _viewInstanceOld = _viewInstanceNew;
        _viewInstanceNew = banner;
        
        if (_isAllowed != enumKIDBAWAdvertisementIsAllowed_Prevented) {
            _statusAds = enumKIDBAWAdvertisementStatus_iAd_Finished;
            [self showAdsWithAnimation:_animationAds];
        }
    }
}

// DON'T USE ADMOD, MOPUB

//#pragma mark - MPAdViewDelegate
//-(UIViewController *)viewControllerForPresentingModalView
//{
//    return _viewControllerAds;
//}
//
//// Sent when an ad request failed.
//- (void)adViewDidFailToLoadAd:(MPAdView *)view
//{
//    if ((_priorityAds & enumKIDBAWAdvertisementPriority_MoPub) == enumKIDBAWAdvertisementPriority_MoPub && _indexAds == enumKIDBAWAdvertisementType_MoPub) {
//        NSLog(@"MP adViewDidFailToLoadAd");
//        [self loadNextAdsType];
//        _statusAds = enumKIDBAWAdvertisementStatus_MoPub_Failed;
//        
//        [self hideAdsWithAnimation:_animationAds];
//    }
//}
//
//// Sent when an ad request loaded an ad.
//- (void)adViewDidLoadAd:(MPAdView *)view
//{
//    if ((_priorityAds & enumKIDBAWAdvertisementPriority_MoPub) == enumKIDBAWAdvertisementPriority_MoPub && _indexAds == enumKIDBAWAdvertisementType_MoPub) {
//        NSLog(@"MP adViewDidLoadAd");
//        
//        _viewInstanceOld = _viewInstanceNew;
//        _viewInstanceNew = view;
//        _statusAds = enumKIDBAWAdvertisementStatus_MoPub_Finished;
//        
//        [self showAdsWithAnimation:_animationAds];
//    }
//}
//
//#pragma mark - GADBannerViewDelegate
//// Sent when an ad request loaded an ad.
//- (void)adViewDidReceiveAd:(GADBannerView *)view
//{
//    if ((_priorityAds & enumKIDBAWAdvertisementPriority_AdMod) == enumKIDBAWAdvertisementPriority_AdMod && _indexAds == enumKIDBAWAdvertisementType_AdMod) {
//        NSLog(@"AdMod adViewDidReceiveAd");
//        [UIView animateWithDuration:1.0 animations:^ {
//            view.frame = _frameShowedAds;
//            
//        }];
//        
//        _viewInstanceOld = _viewInstanceNew;
//        _viewInstanceNew = view;
//        _statusAds = enumKIDBAWAdvertisementStatus_AdMod_Finished;
//        
//        [self showAdsWithAnimation:_animationAds];
//    }
//}
//
//// Sent when an ad request failed.
//- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
//{
//    if ((_priorityAds & enumKIDBAWAdvertisementPriority_AdMod) == enumKIDBAWAdvertisementPriority_AdMod && _indexAds == enumKIDBAWAdvertisementType_AdMod) {
//        NSLog(@"AdMod didFailToReceiveAdWithError %@", error.description);
//        [self loadNextAdsType];
//        _statusAds = enumKIDBAWAdvertisementStatus_AdMod_Failed;
//        
//        [self hideAdsWithAnimation:_animationAds];
//    }
//}

@end
